import "@/public-path";
import { App, createApp } from "vue";
import _App from "./App.vue";
import router from "./router";
import {
  renderWithQiankun,
  qiankunWindow,
  QiankunProps,
} from "vite-plugin-qiankun/dist/helper";

let app: App<Element>;
const render = (props: QiankunProps = {}) => {
  const { container, path } = props;
  app = createApp(_App);
  app.use(router);
  const mountNode = container ? container.querySelector("#app") : "#app";
  if (mountNode) {
    app.mount(mountNode);
  }

  if (path) {
    router.push(props.path);
  }
};

function changeUserListener(e: Event) {
  // store.dispatch((dispatch) => {
  //   dispatch(setUser((e as CustomEvent<User>).detail));
  // });
}

const initQianKun = () => {
  renderWithQiankun({
    bootstrap() {
      console.log("微应用：bootstrap");
    },
    mount(props) {
      // 获取主应用传入数据
      console.log("微应用：mount", props);
      render(props);
      qiankunWindow.addEventListener("changeUser", changeUserListener);
    },
    unmount(props) {
      console.log("微应用：unmount", props);
      app.unmount();
      qiankunWindow.removeEventListener("changeUser", changeUserListener);
    },
    update(props) {
      console.log("微应用：update", props);
    },
  });
};
qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render(); // 判断是否使用 qiankun ，保证项目可以独立运行
